<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="taskRegister"
    @ok="confirmSubmit"
    @close="drawerReset"
    width="850"
    title="新增任务"
    showFooter
    isAbsolute
    getContainer=".page-wrapper"
  >
    <div class="box-drawer">
      <a-form
        hideRequiredMark
        layout="vertical"
        ref="formRef"
        autocomplete="off"
        :model="formState"
        :rules="getFormRules"
        @keypress.enter="confirmSubmit"
      >
        <div class="drawer-box">
          <div class="box-title">项目信息</div>
          <div class="box-form">
            <a-row>
              <a-col :span="24">
                <a-form-item label="部署环境" name="deployEnvir">
                  <a-radio-group v-model:value="formState.deployEnvir" @change="radioChange">
                    <a-radio :value="0">灰度</a-radio>
                    <a-radio :value="1">生产</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="48">
              <a-col :span="12">
                <a-form-item label="系统/模块" name="packageName">
                  <a-tree-select
                    v-model:value="formState.packageName"
                    style="width: 100%"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    placeholder="请选择系统/模块"
                    allow-clear
                    tree-default-expand-all
                    :tree-data="packageArrList"
                    @change="handlePackageChange"
                    :field-names="{
                      children: 'children',
                      label: 'label',
                      value: 'extraValue'
                    }"
                  ></a-tree-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="命名空间" name="nameSpace">
                  <a-select
                    v-model:value="formState.nameSpace"
                    placeholder="请选择命名空间"
                    allowClear
                    :open="selectOpen"
                    @dropdownVisibleChange="(open:boolean)=>dropdownVisibleChange(open,'select')"
                  >
                    <a-select-option
                      :value="item.name"
                      v-for="item in nameSpaceList[formState.deployEnvir]"
                      :key="item.name"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-item label="镜像仓库" name="imageWarehouse">
                  <a-cascader
                    v-model:value="formState.imageWarehouse"
                    allowClear
                    dropdownClassName="custom-cascader-height"
                    @dropdownVisibleChange="(open:boolean)=>dropdownVisibleChange(open,'cascader')"
                    :open="cascaderOpen"
                    :options="imageWarehouseList[formState.deployEnvir]"
                    :load-data="loadData"
                    placeholder="请选择镜像仓库"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>
        <div class="drawer-box">
          <div class="box-title">环境配置</div>
          <div class="box-form">
            <a-row :gutter="48">
              <a-col :span="12">
                <a-form-item label="CPU核数" name="cpu">
                  <a-select v-model:value="formState.cpu" placeholder="请选择CPU核数" allowClear>
                    <a-select-option :value="1"> 1核 </a-select-option>
                    <a-select-option :value="2"> 2核 </a-select-option>
                    <a-select-option :value="4"> 4核 </a-select-option>
                    <a-select-option :value="8"> 8核 </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="内存" name="memory">
                  <a-select v-model:value="formState.memory" placeholder="请选择内存" allowClear>
                    <a-select-option value="1024Mi"> 1024Mi </a-select-option>
                    <a-select-option value="2048Mi"> 2048Mi </a-select-option>
                    <a-select-option value="4096Mi"> 4096Mi </a-select-option>
                    <a-select-option value="8192Mi"> 8192Mi </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="48">
              <a-col :span="12">
                <a-form-item label="副本数" name="replicas">
                  <a-select v-model:value="formState.replicas" placeholder="请选择副本数" allowClear>
                    <a-select-option :value="1"> 1 </a-select-option>
                    <a-select-option :value="2"> 2 </a-select-option>
                    <a-select-option :value="4"> 4 </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>
      </a-form>
    </div>
    <ConfirmTask @register="taskConfirmRegister" @operateSuccess="operateSuccess" />
  </BasicDrawer>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, unref } from 'vue'
import { BasicDrawer, useDrawerInner } from '@/components/Drawer'
import { cloneDeep } from 'lodash-es'
import { message } from 'ant-design-vue'
import type { CascaderProps, SelectProps } from 'ant-design-vue'
import ConfirmTask from './ConfirmTask.vue'
import { useModal } from '@/components/Modal'
import api from '@/api'
import { info } from 'console'

const { listNamespaced, listReposDetails, listRepositoryTags } = api

const emit = defineEmits(['operateSuccess', 'register'])

const formRef = ref()
const formState = reactive({
  deployEnvir: 0,
  cpu: 1,
  imageWarehouse: [],
  memory: '1024Mi',
  nameSpace: null,
  packageName: null,
  replicas: 1
})
const getFormRules = {
  packageName: [{ required: true, message: '请选择系统/模块', trigger: 'change' }],
  nameSpace: [{ required: true, message: '请选择命名空间', trigger: 'change' }],
  imageWarehouse: [{ required: true, message: '请选择镜像仓库', trigger: 'change' }],
  cpu: [{ required: true, message: '请选择CPU核数', trigger: 'change' }],
  memory: [{ required: true, message: '请选择内存', trigger: 'change' }],
  replicas: [{ required: true, message: '请选择副本数', trigger: 'change' }]
}
// 命名空间列表
const nameSpaceList = reactive<any>({
  0: [],
  1: [],
  originPre: [],
  originPrd: []
})
// 镜像仓库列表
const imageWarehouseList = reactive<any>({
  0: [],
  1: [],
  originPre: [],
  originPrd: []
})
const packageArrList = ref<any[]>([])

const initRenderData = ref(false)
const cascaderOpen = ref(false)
const selectOpen = ref(false)

const [taskConfirmRegister, { openModal: taskConfirmOpenModal }] = useModal()

const [taskRegister, { closeDrawer, changeLoading }] = useDrawerInner(async (data) => {
  if (!initRenderData.value) {
    initRenderData.value = true
    packageArrList.value = data.packageList
    try {
      changeLoading(true)
      let namespacedRes = await listNamespaced()
      let reposRes = await listReposDetails({ limit: 99 })
      if (namespacedRes.result?.list && namespacedRes.result?.list.length) {
        let greyArr: any[] = []
        let prodArr: any[] = []
        namespacedRes.result.list.forEach((item: any) => {
          if (item.type === 0) {
            greyArr.push({
              name: item.name,
              matching: item.matching
            })
          } else if (item.type === 1) {
            prodArr.push({
              name: item.name,
              matching: item.matching
            })
          }
        })
        nameSpaceList[0] = greyArr
        nameSpaceList['originPre'] = greyArr
        nameSpaceList[1] = prodArr
        nameSpaceList['originPrd'] = prodArr
      }
      if (reposRes.result?.list && reposRes.result?.list.length) {
        let greyArr: any[] = []
        let prodArr: any[] = []
        reposRes.result.list.forEach((item: any) => {
          if (item.nameType === 0) {
            greyArr.push({
              label: item.name,
              value: item.name,
              namespace: item.namespace,
              isLeaf: false
            })
          } else if (item.nameType === 1) {
            prodArr.push({
              label: item.name,
              value: item.name,
              namespace: item.namespace,
              isLeaf: false
            })
          }
        })
        imageWarehouseList[0] = greyArr
        imageWarehouseList['originPre'] = greyArr
        imageWarehouseList[1] = prodArr
        imageWarehouseList['originPrd'] = prodArr
      }
      changeLoading(false)
    } catch (error) {
      changeLoading(false)
      initRenderData.value = false
    }
  }
})
// 镜像仓库级联选择动态加载
const loadData: CascaderProps['loadData'] = async (selectedOptions) => {
  const targetOption = selectedOptions[selectedOptions.length - 1]
  if (targetOption.initLoad === true) {
    return
  }
  targetOption.loading = true
  try {
    let res = await listRepositoryTags({
      limit: '10',
      namespace: targetOption.namespace,
      repository: targetOption.label
    })
    let children: any[] = []
    if (res.result?.list && res.result?.list.length) {
      res.result.list.forEach((item: any) => {
        children.push({
          label: item.tag + `（${item.updated}）`,
          value: item.tag + '~~' + item.path
        })
      })
    }
    targetOption.children = children
    targetOption.initLoad = true
    targetOption.loading = false
  } catch (error) {
    targetOption.loading = false
  }
}
// 系统/模块变化
const handlePackageChange: SelectProps['onChange'] = (value) => {
  formState.imageWarehouse = []
  formState.nameSpace = null
  if (value) {
    let packageNameArr = String(value).split('~~')
    let deployEnvir = formState.deployEnvir
    if (packageNameArr && packageNameArr.length) {
      let splitPrefix =
        packageNameArr[0].split('-') && packageNameArr[0].split('-').length ? packageNameArr[0].split('-')[0] : ''
      if (deployEnvir === 0) {
        imageWarehouseList[deployEnvir] = imageWarehouseList['originPre'].filter((item: any) => {
          return item.label === `${packageNameArr[0]}-pre`
        })
        nameSpaceList[deployEnvir] = nameSpaceList['originPre'].filter((item: any) => {
          return item.matching === splitPrefix
        })
      } else if (deployEnvir === 1) {
        imageWarehouseList[deployEnvir] = imageWarehouseList['originPrd'].filter((item: any) => {
          return item.label === packageNameArr[0]
        })
        nameSpaceList[deployEnvir] = nameSpaceList['originPrd'].filter((item: any) => {
          return item.matching === splitPrefix
        })
      }
    }
  }
}
// 显示/隐藏浮层的回调
const dropdownVisibleChange = (open: boolean, type: string) => {
  if (open && !formState.packageName) {
    message.warn('请先选择系统/模块')
    unref(formRef).validate('packageName')
  } else {
    if (type === 'cascader') {
      cascaderOpen.value = open
    } else if (type === 'select') {
      selectOpen.value = open
    }
  }
}

const radioChange = (e: Event) => {
  handlePackageChange(formState.packageName as any, [])
}
const drawerReset = () => {
  changeLoading(false)
  unref(formRef).resetFields()
}
const operateSuccess = () => {
  closeDrawer()
  drawerReset()
  emit('operateSuccess')
}
// 提交数据
const confirmSubmit = async () => {
  try {
    await unref(formRef).validate()
    let packageNameArr = String(formState.packageName).split('~~')
    let imageWarehouse = String(formState.imageWarehouse[1]).split('~~')
    let record = {
      cpu: formState.cpu,
      deployEnvir: formState.deployEnvir,
      imageName: formState.imageWarehouse[0],
      imagePath: imageWarehouse[1],
      nameSpace: formState.nameSpace,
      ram: formState.memory,
      replicas: formState.replicas,
      taskDesc: packageNameArr[1],
      taskName: packageNameArr[0],
      taskTag: imageWarehouse[0]
    }
    taskConfirmOpenModal(true, { record })
  } catch (error) {}
}
</script>

<style lang="less" scoped>
.box-drawer {
  padding: 8px 24px;
  .drawer-box {
    margin-bottom: 24px;
    &:last-child {
      margin-bottom: 0;
    }
    .box-title {
      padding-left: 12px;
      padding-bottom: 8px;
      margin-bottom: 16px;
      font-size: 16px;
      font-weight: 600;
      color: @text-color;
      line-height: 22px;
      position: relative;
      border-bottom: 1px solid #e8e8e8;
      &::before {
        content: '';
        width: 4px;
        height: 16px;
        background: @primary-color;
        border-radius: 2px;
        position: absolute;
        left: 0;
        top: 2px;
      }
    }
    .box-form {
      padding: 24px 24px 4px;
      border: 1px solid #e8e8e8;
      border-radius: 2px;
      position: relative;
    }
  }
  :deep(.ant-form-item-label) {
    font-weight: 600;
  }
}
</style>
